package com.ikingtech.platform.business.component.cascade;

import com.ikingtech.framework.sdk.component.api.CompDivisionApi;
import com.ikingtech.framework.sdk.component.model.DivisionElement;
import com.ikingtech.framework.sdk.component.model.DivisionElementQueryParamDTO;
import com.ikingtech.framework.sdk.core.response.R;
import com.ikingtech.framework.sdk.enums.system.division.DivisionLevelEnum;
import com.ikingtech.framework.sdk.web.annotation.ApiController;
import com.ikingtech.framework.sdk.web.annotation.PostRequest;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.Collections;
import java.util.List;

/**
 * @author tie yan
 */
@RequiredArgsConstructor
@ApiController(value = "/component/division/cascade", name = "业务组件-行政区划级联选择", description = "业务组件-行政区划级联选择")
public class DivisionCascadeHandler {

    private final CompDivisionApi divisionApi;

    @PostRequest(order = 1, value = "/list/condition", summary = "按条件查询", description = "按条件查询")
    public R<List<DivisionElement>> listByCondition(@Parameter(name = "queryParam", description = "查询参数")
                                                    @RequestBody DivisionElementQueryParamDTO queryParam) {
        if (null == queryParam.getUpToLevel()) {
            queryParam.setUpToLevel(DivisionLevelEnum.PROVINCE);
        }
        if (null == queryParam.getDownLevel()) {
            queryParam.setDownLevel(DivisionLevelEnum.VILLAGE);
        }
        DivisionLevelEnum currentLevel;
        if (null == queryParam.getParentLevel()) {
            currentLevel = queryParam.getUpToLevel();
        } else {
            currentLevel = switch (queryParam.getParentLevel()) {
                case PROVINCE -> DivisionLevelEnum.CITY;
                case CITY -> DivisionLevelEnum.DISTRICT;
                case DISTRICT -> DivisionLevelEnum.TOWN;
                case TOWN -> DivisionLevelEnum.VILLAGE;
                case VILLAGE, INVALID -> DivisionLevelEnum.INVALID;
            };
        }
        if (queryParam.getUpToLevel().code > currentLevel.code) {
            return R.ok(Collections.emptyList());
        }
        if (queryParam.getDownLevel().code < currentLevel.code) {
            return R.ok(Collections.emptyList());
        }
        return R.ok(this.divisionApi.load(currentLevel, queryParam.getParentCode()));
    }
}
